
#include "my_adc.h"

#if CONFIG_IDF_TARGET_ESP32S2
static uint16_t adc1_chan_mask = BIT(0);
static uint16_t adc2_chan_mask = 0;
static adc_channel_t channel[1] = {ADC1_CHANNEL_0};
#endif
#if CONFIG_IDF_TARGET_ESP32
static uint16_t adc1_chan_mask = BIT(0);
static uint16_t adc2_chan_mask = 0;
static adc_channel_t channel[1] = {ADC1_CHANNEL_0};
#endif


static void continuous_adc_init(uint16_t adc1_chan_mask, uint16_t adc2_chan_mask, adc_channel_t *channel, uint8_t channel_num)
{
    adc_digi_init_config_t adc_dma_config = {
        .max_store_buf_size = 1024,//可以传输的字节大小
        .conv_num_each_intr = TIMES,//一個中斷可以转换的字節數
        .adc1_chan_mask = adc1_chan_mask,//待初始化的通道列表
        .adc2_chan_mask = adc2_chan_mask,
    };
    ESP_ERROR_CHECK(adc_digi_initialize(&adc_dma_config));

    adc_digi_configuration_t dig_cfg = {
        .conv_limit_en = ADC_CONV_LIMIT_EN,//限制ADC转换的次数，在转换conv_limit_num之后就会停止，选择是否使能
        .conv_limit_num = 250,//设置ADC触发器的上限
        .sample_freq_hz = 10 * 1000,//ADC采样频率
        .conv_mode = ADC_CONV_MODE,//选择DMA转换模式，选择使用哪个ADC或者都使用
        .format = ADC_OUTPUT_TYPE,//设置数据输出格式
    };

    adc_digi_pattern_config_t adc_pattern[SOC_ADC_PATT_LEN_MAX] = {0};//将使用ADC通道的配置列表
    dig_cfg.pattern_num = channel_num;
    for (int i = 0; i < channel_num; i++) {
        uint8_t unit = GET_UNIT(channel[i]);
        uint8_t ch = channel[i] & 0x7;//ADC通道，总共0-7八个通道，只看后三位
        adc_pattern[i].atten = ADC_ATTEN_DB_11;//衰减
        adc_pattern[i].channel = ch;//通道
        adc_pattern[i].unit = unit;//索引
        adc_pattern[i].bit_width = SOC_ADC_DIGI_MAX_BITWIDTH;//设置位宽为最大宽度

        ESP_LOGI(TAG, "adc_pattern[%d].atten is :%x", i, adc_pattern[i].atten);
        ESP_LOGI(TAG, "adc_pattern[%d].channel is :%x", i, adc_pattern[i].channel);
        ESP_LOGI(TAG, "adc_pattern[%d].unit is :%x", i, adc_pattern[i].unit);
    }
    dig_cfg.adc_pattern = adc_pattern;
    ESP_ERROR_CHECK(adc_digi_controller_configure(&dig_cfg));
}


bool check_valid_data(const adc_digi_output_data_t *data)//判断数据是不是有效的
{
    const unsigned int unit = data->type2.unit;
    if (unit > 2) {
        return false;
    }
    if (data->type2.channel >= SOC_ADC_CHANNEL_NUM(unit)) {
        return false;//判断通道数是不是配置多了
    }
    
    return true;
}

void my_adc_dma_init(void)
{
    continuous_adc_init(adc1_chan_mask, adc2_chan_mask, channel, sizeof(channel) / sizeof(adc_channel_t));//初始化配置
}
